package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.mall.dto.ProductParam;
import com.pdd.mall.entity.Product;
import com.pdd.mall.mapper.ProductMapper;
import com.pdd.mall.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Page<Product> getProductList(String keyword, Long categoryId, Double minPrice, Double maxPrice, Integer pageNum, Integer pageSize, String sortField, String sortOrder) {
        Page<Product> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 只查询上架的商品

        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper.like("name", keyword).or().like("description", keyword));
        }

        // 分类筛选
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }

        // 价格范围筛选
        if (minPrice != null) {
            queryWrapper.ge("price", minPrice);
        }

        if (maxPrice != null) {
            queryWrapper.le("price", maxPrice);
        }

        // 排序
        if (StringUtils.hasText(sortField)) {
            if ("asc".equalsIgnoreCase(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
        } else {
            queryWrapper.orderByDesc("create_time");
        }

        return productMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Product getProductDetail(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    public Page<Product> getMerchantProductList(Long merchantId, String keyword, Long categoryId, Integer status, Integer pageNum, Integer pageSize, String sortField, String sortOrder) {
        System.out.println("ProductService.getMerchantProductList - 参数: merchantId=" + merchantId +
                          ", keyword=" + keyword + ", categoryId=" + categoryId +
                          ", status=" + status + ", pageNum=" + pageNum + ", pageSize=" + pageSize +
                          ", sortField=" + sortField + ", sortOrder=" + sortOrder);

        Page<Product> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", merchantId);

        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper.like("name", keyword).or().like("description", keyword));
        }

        // 分类筛选
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }

        // 状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        // 排序
        if (StringUtils.hasText(sortField)) {
            if ("asc".equalsIgnoreCase(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
        } else {
            queryWrapper.orderByDesc("create_time");
        }

        System.out.println("执行SQL查询: " + queryWrapper.getSqlSegment());
        Page<Product> result = productMapper.selectPage(page, queryWrapper);
        System.out.println("查询结果: 总记录数=" + result.getTotal() + ", 当前页记录数=" + result.getRecords().size());

        // 打印查询到的商品信息
        if (result.getRecords().size() > 0) {
            System.out.println("查询到的商品列表:");
            for (Product product : result.getRecords()) {
                System.out.println("  商品ID: " + product.getId() + ", 名称: " + product.getName() +
                                  ", 商家ID: " + product.getMerchantId() + ", 状态: " + product.getStatus());
            }
        } else {
            System.out.println("未查询到任何商品");
        }

        return result;
    }

    @Override
    public Product getMerchantProductDetail(Long id, Long merchantId) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("merchant_id", merchantId);
        return productMapper.selectOne(queryWrapper);
    }

    @Override
    public Product addProduct(ProductParam param, Long merchantId) {
        Product product = new Product();
        BeanUtils.copyProperties(param, product);
        product.setMerchantId(merchantId);

        // 设置默认状态
        if (product.getStatus() == null) {
            product.setStatus(1); // 默认上架
        }

        productMapper.insert(product);
        return product;
    }

    @Override
    public Product updateProduct(Long id, ProductParam param, Long merchantId) {
        Product product = getMerchantProductDetail(id, merchantId);
        if (product == null) {
            return null;
        }

        BeanUtils.copyProperties(param, product);
        // 确保商家ID不被覆盖
        product.setMerchantId(merchantId);
        productMapper.updateById(product);
        return product;
    }

    @Override
    public boolean deleteProduct(Long id, Long merchantId) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("merchant_id", merchantId);
        return productMapper.delete(queryWrapper) > 0;
    }

    @Override
    public boolean updateProductStatus(Long id, Integer status, Long merchantId) {
        Product product = getMerchantProductDetail(id, merchantId);
        if (product == null) {
            return false;
        }

        product.setStatus(status);
        return productMapper.updateById(product) > 0;
    }
}
